<?php
namespace app\customer\controller;
use think\Controller;
use think\Db;
class Login extends Controller{
    public function login(){
        return $this->fetch();
    }
    public function doLogin(){
    	$account = input("param.account");
        $password = input("param.password");
        $verifycode = input("param.verifycode");
        $hasUser = Db::name('customer')->where(['account'=> $account,'state'=>1])->find();
        if(empty($hasUser)){
        	return json(['code' => 501, 'url' => '', 'msg' => '用户不存在']);
        }elseif(md5('tmd'.$password)!=$hasUser['password']){
        	return json(['code' => 502, 'url' => '', 'msg' => '密码错误']);
        }elseif(!captcha_check($verifycode)){
        	return json(['code' => 503, 'url' => '', 'msg' => '验证码错误']);
		}else{
        	session('account', $account);
            session('customer',$hasUser);
			// cookie('password', $password, 3600);
        	return json(['code' => 200, 'url' => url('index/index'), 'msg' => '成功登录']);
        }
    }
    public function edit(){
        if(request()->isGet()){
            return $this->fetch();
        }elseif(request()->isPost()){
            $passworded = input("param.passworded");
            $password = input("param.password");
            if($password==$passworded){
                return json(['code' => 503, 'msg' => '新旧密码不能相同']);
            }
            if(md5('tmd'.$passworded)!=session('customer')['password']){
                return json(['code' => 501, 'msg' => '旧密码错误']);
            }elseif(md5('tmd'.$passworded)==session('customer')['password']){
                if(empty($password)){
                    return json(['code' => 502, 'msg' => '新密码不能为空']);
                }else{
                    $res=Db::name('customer')->where(['id'=>session('customer')['id']])->update(['password'=>md5('tmd'.$password)]);
                    if($res){
                        $hasUser = Db::name('customer')->where(['id'=>session('customer')['id']])->find();
                        session('customer',$hasUser);
                        return json(['code' => 200, 'msg' => '修改成功']);
                    }else{
                        return json(['code' => 500, 'msg' => '修改失败']);
                    }
                }
            }
        }
    }
    public function loginOut(){
    	session(null);
    	// cookie('password',null);
        $this->redirect(url('login/login'));
    }
}
